<template>
	<div class="music" :class="[isplaying?'playing':'']" @click="stopmusic">
		<image :src="musicImg" />
	</div>
</template>

<script>
	export default {
		name: "music",
		props: {
			music: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				musicsrc: '',
				innerAudioContext: null,
				isplaying: true,
				musicImg: ""
			}
		},
		mounted() {
			if(this.music){
				this.startmusic(this.music)
			}
		},
		methods: {
			startmusic(music) {
				let that = this;
				this.innerAudioContext = uni.createInnerAudioContext();
				this.innerAudioContext.autoplay = true;
				this.innerAudioContext.src = music;
				this.innerAudioContext.loop = true;
				this.innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
			},
			stopmusic() {
				if (this.isplaying) {
					this.innerAudioContext.pause();
					this.isplaying = false;
				} else {
					this.innerAudioContext.play();
					this.isplaying = true;
				}
			},
		},
		beforeDestroy: function() {
			//离开页面是停止播放音乐
			this.innerAudioContext.stop();
		},
	}
</script>

<style lang="scss" scoped>
	.music {
		opacity: 1;
		height: 70rpx;
		color: white;
		width: 70rpx;
		position: absolute;
		right: 10rpx;
		top: 10%;

		&.playing {
			animation: rotate2d 2s linear infinite;
			-webkit-animation: rotate2d 2s linear infinite;
		}

		&.play {
			opacity: 1;
			height: 50rpx;
			color: white;
			font-size: 32rpx;
			position: fixed;
			padding-left: 30rpx;
			right: 12rpx;
			top: 10%;
		}

		image {
			width: 70rpx;
			height: 70rpx;
		}

	}
	
	@-webkit-keyframes rotate2d {
	  0% {
	    -webkit-transform: rotate(0deg);
	    transform: rotate(0deg)
	  }
	
	  to {
	    -webkit-transform: rotate(1turn);
	    transform: rotate(1turn)
	  }
	}
	
</style>